#include "ChatTask.h"

ChatTask::ChatTask(char *body, int len, int clientfd) : BaseTask(body, len, clientfd)
{
}

ChatTask::~ChatTask()
{
}

void ChatTask::work(SharedMemoryIPC*ipc)
{
    HEAD head={0};
    CHAT_REQ chat_req = {0};
    CHAT_RESP chat_resp = {0};
    char send_buffer[1024]={0};
    memcpy(&chat_req, m_body,m_len);
    if (CData::user.count(chat_req.recv_id) == 0)
    {
        chat_resp.status = 1;
        strcpy(chat_resp.msg, "用户不在线");
        // 发送给客户端
        bzero(&head, sizeof(head));
        head.service_type = CHATRESP;
        head.data_len = sizeof(chat_resp);
        bzero(send_buffer, sizeof(send_buffer));
        memcpy(send_buffer,&CData::user[chat_req.send_id],sizeof(int));
        memcpy(send_buffer+sizeof(int), &head, sizeof(HEAD));
        memcpy(send_buffer + sizeof(HEAD)+sizeof(int), &chat_resp, head.data_len);
        ipc->write_shm(send_buffer);
        UserModel model;
        bool st=model.insert_chat(chat_req.send_id,chat_req.recv_id,chat_req.msg);
        if(st) cout<<"消息成功插入数据库"<<endl;
    }
    else // 发送给对应的客户端
    {
        //发送响应给发送者客户端
        chat_resp.status = 0;
        bzero(&head, sizeof(head));
        strcpy(chat_resp.msg, "发送成功");
        head.service_type = CHATRESP;
        head.data_len = sizeof(chat_resp);
        bzero(send_buffer, sizeof(send_buffer));
        memcpy(send_buffer,&CData::user[chat_req.send_id],sizeof(int));
        memcpy(send_buffer+sizeof(int), &head, sizeof(HEAD));
        memcpy(send_buffer + sizeof(HEAD)+sizeof(int), &chat_resp, head.data_len);
       // write(CData::user[chat_req.send_id], send_buffer, sizeof(HEAD) + head.data_len);
       cout<<"-----------------------------测试----------------------------------------"<<endl;
       int fd=0;
       memcpy(&fd,send_buffer,sizeof(int));
       cout<<"fd="<<fd<<endl;
       ipc->write_shm(send_buffer);
//--------------------------------------------------------------------------------------------
        // 把数据发送到对于的客户端
        head.service_type = CHATREQ;
        head.data_len=m_len;
        bzero(send_buffer, sizeof(send_buffer));
        memcpy(send_buffer,&CData::user[chat_req.recv_id],sizeof(int));
        memcpy(send_buffer+sizeof(int), &head, sizeof(HEAD));
        memcpy(send_buffer + sizeof(HEAD)+sizeof(int), &chat_req, head.data_len);
       // write(CData::user[chat_req.recv_id], send_buffer, sizeof(HEAD) +head.data_len);
        ipc->write_shm(send_buffer);

        UserModel model;
       bool st=model.insert_chat(chat_req.send_id,chat_req.recv_id,chat_req.msg);
       if(st) cout<<"消息成功插入数据库"<<endl;
    }
}
